package com.example.matchandroiddevices.test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

public class UsbPermissionReceiver extends BroadcastReceiver {
    private static final String TAG = "UsbPermissionReceiver";
    private static final String ACTION_USB_PERMISSION = "com.example.matchandroiddevices.USB_PERMISSION";

    private final UsbPermissionListener listener;

    public interface UsbPermissionListener {
        void onPermissionGranted(UsbDevice device);
        void onPermissionDenied(UsbDevice device);
    }

    public UsbPermissionReceiver(UsbPermissionListener listener) {
        this.listener = listener;
    }
    public UsbPermissionReceiver(){
        this.listener = null;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null) {
                    boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
                    if (granted) {
                        Log.d(TAG, "Permission granted for device: " + device.getDeviceName());
                        if (listener != null) {
                            listener.onPermissionGranted(device);
                        }
                    } else {
                        Log.d(TAG, "Permission denied for device: " + device.getDeviceName());
                        if (listener != null) {
                            listener.onPermissionDenied(device);
                        }
                    }
                }
            }
        }
    }

    public static String getActionString() {
        return ACTION_USB_PERMISSION;
    }
}